package cn.skyclass.net
{
	import cn.skyclass.utils.StringUtil;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	
	/**
	 * web service 调用结果的包装类
	 * 用于获取各种数据类型的结果
	 */
	public class ResultWrapper
	{
		/**
		 * result : web service 调用结果事件
		 */
		public function ResultWrapper(result:ResultEvent){
			this.result = result;
		}
		
		private var result:ResultEvent;
		
		
		/**
		 * 使用此结果值来填充生成 bean 列表
		 * 用于处理服务器端的 web service 返回对象列表的情况
		 */
		public function getBeanArray(beanCla:Class):ArrayCollection{
			var out:ArrayCollection = new ArrayCollection();
			if(!result || !result.result || !beanCla){ return out; }
			
			var datasource:ArrayCollection = result.result as ArrayCollection;
			if(datasource == null){
				out.addItem(createBean(beanCla, result.result));				
			}else{			
				for each(var obj:Object in datasource){
					out.addItem(createBean(beanCla, obj));
				}
			}
			return out;
		}
		
		/**
		 * 使用此结果值来填充生成一个 bean 对象
		 * 用于处理服务器端的 web service 返回一个对象的情况
		 */		
		public function getBeanObject(beanCla:Class):Object{
			if(!result || !result.result || !beanCla){ return null; }
			
			return createBean(beanCla, result.result);
		}	
		
		/**
		 * 根据给定的对象数据创建一个 bean 对象
		 */		
		protected function createBean(beanCla:Class, beanData:Object):Object{
			var out:Object = new beanCla();
			if(out is IRpcBean){
				IRpcBean(out).fillWith(beanData);
			}else{
		        for (var prop:String in beanData){
		        	try{
		        		if(out.hasOwnProperty(prop)){
		        			out[prop] = beanData[prop];
		        		}
		            }catch(err:Error){	            	         	
		            	trace(err);
		            }
		        }	     					
			}
			return out;	
		}
		
		
		public function getBoolean():Boolean{
			if(!result || !result.result) {
				return false;
			}else{
				return StringUtil.getBoolValue(String(result.result));
			}
		}
		
		public function getNumber():Number{
			var out:Number = Number(result.result);
			return out ? out : 0;
		}
		
		public function getString():String{
			return String(result.result);
		}	
		
		public function getIntList():ArrayCollection{
			var out:ArrayCollection = new ArrayCollection();
			var datasource:ArrayCollection = result.result as ArrayCollection;
			if(datasource == null){
				out.addItem(int(result.result));
			}else{			
				for each(var o:Object in datasource){
					out.addItem(int(o));
				}		
			}			
			return out;
		}

			
	}
}